#!/bin/sh

releaseType=""
phase=0
case "$1" in
	major|minor|patch) releaseType=$1 ;;
	-c) phase=1 ;;
	*)
		echo "no release type given or -c given"
		exit 1
		;;
esac

if [ $phase -eq 0 ]
then
	if [ "$(git status -s | wc -l)" -ne 0 ]
	then
		echo "uncommited changes"
		git status -s
		echo "continue? [y/N]"
		read -r decision
		if [ "$decision" != 'y' ]
		then
			echo 'aborting'
			exit 0
		fi
	fi

	if [ "$(git log '@{u}..' | wc -l)" -ne 0 ]
	then
		echo "unpushed changes"
		git status -s
		echo "continue? [y/N/p]"
		read -r decision
		if [ "$decision" != 'y' ]
		then
			echo 'aborting'
			exit 0
		elif [ "$decision" = 'p' ]
		then
			git push
			sleep 5
		fi
	fi

	retry="1"
	latestCI=$(curl https://ci.apiote.xyz/toys/czwek-commitly/latest 2>/dev/null)
	latestCIstatus=$(echo "$latestCI" | grep '<h2' | sed 's/<h2[^>]*>//' | sed 's|</h2>||' | grep -oE '[A-Z]+')
	latestCIstarted=$(echo "$latestCI" | grep -oE '[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]+\+[0-9]{2}:[0-9]{2}' | head -n1)
	while [ "$latestCIstatus" != 'OK' ] && [ "$retry" = "1" ]
	do
		echo "latest CI started at $latestCIstarted result is $latestCIstatus, not OK"
		echo "retry? [y/N]"
		read -r decision
		if [ "$decision" != 'y' ]
		then
			retry="0"
			exit 1
		fi
	done

	currentVersionName=$(grep 'versionName' app/build.gradle | tr -s ' ' | cut -d ' ' -f3 | tr -d '"')
	major=$(echo "$currentVersionName" | cut -d '.' -f1)
	minor=$(echo "$currentVersionName" | cut -d '.' -f2)
	patch=$(echo "$currentVersionName" | cut -d '.' -f3)
	currentVersionCode=$(grep 'versionCode' app/build.gradle | tr -s ' ' | cut -d ' ' -f3)

	case $releaseType in
		major) newVersionName="$((major + 1)).0.0" ;;
		minor) newVersionName="${major}.$((minor + 1)).0" ;;
		patch) newVersionName="${major}.${minor}.$((patch + 1))" ;;
		*) echo "wrong release type given"; exit 1 ;;
	esac
	newVersionCode=$((currentVersionCode + 1))

	sed -i "s/versionName \"$currentVersionName\"/versionName \"$newVersionName\"/" app/build.gradle
	sed -i "s/versionCode $currentVersionCode/versionCode $newVersionCode/" app/build.gradle

	git shortlog "v${currentVersionName}..HEAD" >> "metadata/en-US/changelogs/$newVersionCode.txt"

	echo "time to update changelogs"
elif [ $phase -eq 1 ]
then
	newVersionName=$(grep 'versionName' app/build.gradle | tr -s ' ' | cut -d ' ' -f3 | tr -d '"')
	newVersionCode=$(grep 'versionCode' app/build.gradle | tr -s ' ' | cut -d ' ' -f3)
	if ! find metadata -type d -name changelogs -print0 | xargs -0 -I{} [ -f "{}/$newVersionCode.txt" ]
	then
		echo "not all languages have changelog"
		exit 1
	fi
	git add app/build.gradle
	git add metadata/
	git commit -S -m "release version $newVersionName ($newVersionCode)"
	git push
	git switch master
	git merge -S --no-ff -m "merge develop into master for version $newVersionName" develop
	git tag -s -m "v${newVersionName}" "v${newVersionName}"
	git push origin --tags
	git switch develop
	git merge master
fi
